package com.chainyoung.component_tmperson.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.view.PinView;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.common.appcommon.hdwallet.CoinConstant;
import com.chainyoung.common.appcommon.hdwallet.OwnWalletUtils;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.ui.activity.hdwallet.ImportHdWalletActivity;
import com.chainyoung.component_tmperson.ui.mvp.contract.ConfirmPinCodeContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.ConfirmPinCodePresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;

import java.util.List;

import butterknife.BindView;

import static com.chainyoung.router.RouterConstants.PATH_VALIDATE_CODE;

@Route(path = PATH_VALIDATE_CODE)
public class ConfirmPinCodeActivity extends BaseActivity<ConfirmPinCodePresenter> implements ConfirmPinCodeContract.View {


    @BindView(R2.id.pinView)
    PinView pinView;

    private String pinCode;
    private String TAG = getClass().getSimpleName();

    private boolean isValidateOld;
    private boolean isValidateFirst;
    private boolean isFromOtherApp;
    private boolean isImportWallet;
    private boolean isCreateWallet;

    private String coinType = CoinConstant.ETH;
    private HdWalletCache hdWallet;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        pinCode = getIntent().getStringExtra("pinCode");
        isValidateOld = getIntent().getBooleanExtra("validateOld", false);//验证旧Code
        isValidateFirst = getIntent().getBooleanExtra("validateFirst", false);//开机验证
        isFromOtherApp = getIntent().getBooleanExtra(LibConstant.FROM_OTHER_APP, false);//其他app调起本APP
        isImportWallet = getIntent().getBooleanExtra("isImportWallet", false);//导入钱包
        isCreateWallet = getIntent().getBooleanExtra("isCreateWallet", false);//创建钱包
        coinType = getIntent().getStringExtra("coinType");

        setCurrentTitle(getString(isValidateOld ? R.string.tmperson_reset_pin_code : R.string.tmperson_validate_pin_code));
        pinView.setPinViewEventListener(new PinView.PinViewEventListener() {
            @Override
            public void onDataEntered(final PinView pinview, boolean fromUser) {

                if (isValidateFirst) {
                    if (!pinview.getValue().equals(pinCode)) {
//                        ToastUtil.showToast("您的PIN码输入有误");
//                        pinview.clearValue();
                        KProgressHUD.create(mContext)
                                .setCustomView(mContext, R.drawable.tips_error)
                                .setLabel(getString(R.string.tmperson_pincode_uncorrect))
                                .show().setDuration(1500);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                pinview.clearValue();
                            }
                        }, 1500);
                        return;
                    } else {
                        closeKeybord();
                        RouterUtils.getInstance()
                                .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                                .withInt("page", 0)
                                .navigation(mContext);
                        finish();
                    }
                }

                if (isValidateOld) {
                    if (!pinView.getValue().equals(pinCode)) {
//                        ToastUtil.showToast("您的PIN码输入有误");
//                        pinview.clearValue();
                        KProgressHUD.create(mContext)
                                .setCustomView(mContext, R.drawable.tips_error)
                                .setLabel(getString(R.string.tmperson_pincode_uncorrect))
                                .show().setDuration(1500);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                pinview.clearValue();
                            }
                        }, 1500);
                        return;
                    } else {
                        closeKeybord();
                        Intent intent = new Intent(mContext, SetPinCodeActivity.class);
                        intent.putExtra("isReset", true);
                        mContext.startActivity(intent);
                        finish();
                    }
                }

                if (isFromOtherApp) {
                    if (!pinView.getValue().equals(pinCode)) {
//                        ToastUtil.showToast("您的PIN码输入有误");
//                        pinview.clearValue();
                        KProgressHUD.create(mContext)
                                .setCustomView(mContext, R.drawable.tips_error)
                                .setLabel(getString(R.string.tmperson_pincode_uncorrect))
                                .show().setDuration(1500);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                pinview.clearValue();
                            }
                        }, 1500);
                        return;
                    } else {
                        closeKeybord();
                        RouterUtils.getInstance()
                                .build(RouterConstants.PATH_MAKE_CASH)
                                .withBoolean(LibConstant.FROM_OTHER_APP, true)
                                .navigation(mContext);
                        finish();
                    }
                }


                if (!isValidateOld && !isValidateFirst && !isFromOtherApp) {
                    if (!pinView.getValue().equals(pinCode)) {
//                        ToastUtil.showToast("您的PIN码输入有误");
//                        pinview.clearValue();
                        KProgressHUD.create(mContext)
                                .setCustomView(mContext, R.drawable.tips_error)
                                .setLabel(getString(R.string.tmperson_pincode_uncorrect))
                                .show().setDuration(1500);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                pinview.clearValue();
                            }
                        }, 1500);
                        return;
                    }
                    closeKeybord();
                    SPUtil.getInstance().put(LibConstant.PIN_CODE, pinview.getValue());
                    if (isCreateWallet) {
                        createWallet(pinview.getValue(), coinType);
                    } else if (isImportWallet) {
                        Intent intent = new Intent(mContext, ImportHdWalletActivity.class);
                        intent.putExtra("coinType", coinType);
                        mContext.startActivity(intent);
                        finish();
                    } else {
                        finish();
                    }

                }

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_confirm_pin_code;
    }


    /**
     * 创建 钱包
     */
    private void createWallet(String password, String coinType) {
        hdWallet = OwnWalletUtils.createNewAccount(password, coinType);
        mPresenter.getAllHdWalletCaches(hdWallet.getCoinType());
    }


    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                .withInt("page", 3)
                .withBoolean("isGetWallet", true)
                .navigation(mContext);
        finish();
    }

    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        // 给新增钱包取名
        int num = datas == null ? 1 : datas.size() + 1;
        hdWallet.setWalletName(hdWallet.getCoinType() + "-" + num);
        mPresenter.addHdWalletCache(hdWallet);

    }

    /**
     * 关闭软键盘
     */
    public void closeKeybord() {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.hideSoftInputFromWindow(pinView.getWindowToken(), 0);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeKeybord();
    }
}
